import React, { useEffect, useMemo, useState } from 'react';
import {
  HomeOutlined,
  DashboardOutlined,
  UserOutlined,
  DatabaseOutlined,
  SettingOutlined,
  RobotOutlined,
  BookOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Breadcrumb, Layout, Menu, theme, ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';
import { Outlet, useLocation, useNavigate, Link } from 'react-router-dom';
import { tworouter } from './router/Index';


function App() {
  const nav=useNavigate()
  const {pathname}=useLocation()
  const { Header, Content,  Sider } = Layout;

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

// const items: MenuItem[] = [
//   getItem('Option 1', '1', <PieChartOutlined />),
//   getItem('Option 2', '2', <DesktopOutlined />),
//   getItem('User', 'sub1', <UserOutlined />, [
//     getItem('Tom', '3'),
//     getItem('Bill', '4'),
//     getItem('Alex', '5'),
//   ]),
//   getItem('Team', 'sub2', <TeamOutlined />, [getItem('Team 1', '6'), getItem('Team 2', '8')]),
//   getItem('Files', '9', <FileOutlined />),
// ];
const getIcon = (path: string) => {
  switch (path) {
    case '/home':
      return <HomeOutlined />;
    case '/view':
    case '/view/index':
      return <DashboardOutlined />;
    case '/AI':
      return <UserOutlined />;
    case '/order':
      return <DatabaseOutlined />;
    case '/set':
      return <SettingOutlined />;
    case '/docs':
    case '/docs/guide':
    case '/docs/faq':
      return <BookOutlined />;
    default:
      return <DashboardOutlined />;
  }
}

const erji=(arr)=>{
  return arr.map((item)=>{
    return {
      key:item.path,
      icon:getIcon(item.path),
      children:item.children?erji(item.children):null,
      label:item.title
    }
  })
}
// 根据角色过滤菜单（非管理员隐藏创作中心）
const items = useMemo(() => {
  const raw = localStorage.getItem('auth_user')
  let role: string | null = null
  try { role = raw ? (JSON.parse(raw)?.role || null) : null } catch { role = null }
  const isAdmin = role === 'admin'
  const deny = new Set<string>(isAdmin ? [] : ['/worker'])
  const walk = (arr:any[]) => arr
    .filter(r => !deny.has(r.path))
    .map(r => ({ ...r, children: r.children ? walk(r.children) : undefined }))
  return erji(walk(tworouter))
}, [pathname])

// const App: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  // preferences
  const [mode, setMode] = useState<'light'|'dark'>(() => (localStorage.getItem('pref.themeMode') as 'light'|'dark') || 'light')
  const [primary, setPrimary] = useState<string>(() => localStorage.getItem('pref.primary') || '#3b5bfd')
  const [localeKey, setLocaleKey] = useState<string>(() => localStorage.getItem('pref.locale') || 'zh-CN')

  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent).detail || {}
      if (detail.themeMode) setMode(detail.themeMode)
      if (detail.primary) setPrimary(detail.primary)
      if (detail.locale) setLocaleKey(detail.locale)
      // also read from storage as source of truth
      const m = localStorage.getItem('pref.themeMode') as 'light'|'dark' | null
      const p = localStorage.getItem('pref.primary')
      const l = localStorage.getItem('pref.locale')
      if (m) setMode(m)
      if (p) setPrimary(p)
      if (l) setLocaleKey(l)
    }
    window.addEventListener('pref:update', handler as EventListener)
    return () => window.removeEventListener('pref:update', handler as EventListener)
  }, [])

  const localeObj = useMemo(() => localeKey === 'en-US' ? enUS : zhCN, [localeKey])
  const algo = useMemo(() => mode === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm, [mode])
  const {
    token: { colorBgContainer, borderRadiusLG, colorBorder },
  } = theme.useToken();

  const titleMap = useMemo(() => {
    const m = new Map<string, string>()
    const walk = (arr: any[]) => {
      arr.forEach((r: any) => {
        if (r.path && r.title) m.set(r.path, r.title)
        if (r.children) walk(r.children)
      })
    }
    walk(tworouter as any)
    return m
  }, [])

  const breadcrumbItems = useMemo(() => {
    const segs = pathname.split('/').filter(Boolean)
    const acc: string[] = []
    const items: { title: React.ReactNode }[] = []
    segs.forEach((seg) => {
      const p = '/' + [...acc, seg].join('/')
      acc.push(seg)
      const t = titleMap.get(p)
      if (t) items.push({ title: <Link to={p}>{t}</Link> })
    })
    return items.length ? items : [{ title: <Link to="/home">首页</Link> }]
  }, [pathname, titleMap])

  // 读取当前登录用户（在路由变化时刷新）
  const currentUser = useMemo(() => {
    try {
      const raw = localStorage.getItem('auth_user')
      return raw ? JSON.parse(raw) : null
    } catch {
      return null
    }
  }, [pathname])

  const handleLogout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('auth_user')
    nav('/login')
  }

  return (
    <ConfigProvider
      locale={localeObj}
      theme={{ algorithm: algo, token: { colorPrimary: primary } }}
    >
      <Layout style={{ minHeight: '100vh', background: colorBgContainer }}>
      <Sider theme="light" collapsible collapsed={collapsed} onCollapse={(value) => setCollapsed(value)} style={{ borderRight: `1px solid ${colorBorder}` }}>
        <div className="demo-logo-vertical" style={{ height: 64, display: 'flex', alignItems: 'center', justifyContent: collapsed ? 'center' : 'flex-start', padding: collapsed ? 0 : '0 16px', fontWeight: 700, fontSize: collapsed ? 16 : 18, gap: 8 }}>
          <RobotOutlined />
          {collapsed ? '数字人' : '数字人管理系统'}
        </div>
        <Menu theme="light" selectedKeys={[pathname]} mode="inline" items={items} 
        onClick={({key})=>nav(key)}/>
      </Sider>
      <Layout style={{ background: colorBgContainer }}>
        <Header style={{ padding: '8px 16px', background: colorBgContainer, borderBottom: `1px solid ${colorBorder}` }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: '100%' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ color: '#999' }}>当前位置：</span>
              <Breadcrumb items={breadcrumbItems} />
            </div>
            <div style={{ display:'flex', alignItems:'center', gap: 12 }}>
              <span style={{ color: '#666' }}>用户：{currentUser?.username || '未登录'}</span>
              {currentUser ? (
                <a onClick={handleLogout}>退出登录</a>
              ) : (
                <Link to="/login">去登录</Link>
              )}
            </div>
          </div>
        </Header>
        <Content style={{ margin: 0, background: colorBgContainer, border: `1px solid ${colorBorder}`, borderTop: 0, borderLeft: 0, boxSizing: 'border-box', padding: 16 }}>
          <div
            style={{
              minHeight: 360,
              background: 'transparent',
              borderRadius: 0,
              padding: 0,
            }}
          >
           <Outlet></Outlet>
          </div>
        </Content>
       
      </Layout>
    </Layout>
    </ConfigProvider>
  )
}

export default App
